package com.company.project.web.auth;

import com.company.project.config.jwt.JwtAuthenticationRequest;
import com.company.project.config.jwt.JwtAuthenticationResponse;
import com.company.project.core.Result;
import com.company.project.core.ResultGenerator;
import com.company.project.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping(value = "/auth")
@Api(tags = "登录/注册")
public class AuthController {
    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private AuthService authService;

    /**
     * 根据账号获取token
     *
     * @param authenticationRequest
     * @return 传出结果集
     */
    @ApiOperation(value = "登录", notes = "登录并获取token的接口")
    @PostMapping(value = "${jwt.route.authentication.login}")
    public Result createAuthenticationToken(
            @RequestBody JwtAuthenticationRequest authenticationRequest) throws AuthenticationException {
        Result result = ResultGenerator.genFailResult("账号或密码错误");
        try {
            final String token = authService.login(authenticationRequest.getUsername(), authenticationRequest.getPassword());
            ResponseEntity<?> responseEntity = ResponseEntity.ok(new JwtAuthenticationResponse(token));
            result = ResultGenerator.genSuccessResult(responseEntity);
            return result;
        } catch (Exception e) {
            return result;
        }
    }

    @RequestMapping(value = "${jwt.route.authentication.refresh}", method = RequestMethod.GET)
    public ResponseEntity<?> refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws AuthenticationException {
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        if (refreshedToken == null) {
            return ResponseEntity.badRequest().body(null);
        } else {
            return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken));
        }
    }

    @RequestMapping(value = "${jwt.route.authentication.register}", method = RequestMethod.POST)
    public Integer register(@RequestBody User addedUser) throws AuthenticationException {
        return authService.register(addedUser);
    }
}
